package com.webxiaohua.thread.deadlock;

/**
 * @author shenxinhua
 * @date 2019-06-23 11:54
 * @desc 死锁测试
 */
public class DeadLock {
    private static Integer countA = new Integer(0);
    private static Integer countB = new Integer(0);

    public static void main(String... args){
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (countA){
                    System.out.println("线程："+Thread.currentThread().getName()+"已经获得countA对象锁");
                    try{
                        Thread.sleep(5000);
                        System.out.println("线程："+Thread.currentThread().getName()+"尝试获取countB对象锁");
                    }catch(InterruptedException ex){
                        ex.printStackTrace();
                    }
                    synchronized (countB){
                        System.out.println("线程："+Thread.currentThread().getName()+"已经获得countB对象锁");
                    }
                }
                System.out.println("线程："+Thread.currentThread().getName()+"执行完成");
            }
        },"A");
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (countB){
                    System.out.println("线程："+Thread.currentThread().getName()+"已经获得countB对象锁");
                    try{
                        Thread.sleep(5000);
                        System.out.println("线程："+Thread.currentThread().getName()+"尝试获取countA对象锁");
                    }catch(InterruptedException ex){
                        ex.printStackTrace();
                    }
                    synchronized (countA){
                        System.out.println("线程："+Thread.currentThread().getName()+"已经获得countA对象锁");
                    }
                }
                System.out.println("线程："+Thread.currentThread().getName()+"执行完成");
            }
        },"B");
        thread1.start();
        thread2.start();
    }
}
